import engine from "./engine"
import { BoxGeometry, MeshLambertMaterial, Mesh, PointLight, GridHelper, ShaderMaterial, Raycaster, AmbientLight, Vector3 } from 'three'
import shader from './shader'

let renderTo = null

export default (function () {
    engine.mScene.clear()

    shader.then((shadersList) => {
        console.log(shadersList)
    })

    let geometry = new BoxGeometry(1, 1, 1) //创建一个立方体几何对象Geometry
    let material = new MeshLambertMaterial({ color: 0x0000ff }) //材质对象Material
    let mesh = new Mesh(geometry, material) //网格模型对象Mesh
    const raycasterIgnore = [GridHelper]

    let point = new PointLight(0xffffff)
    let point2 = new PointLight(0xffffff)
    let ambient = new AmbientLight(0x444444)
    point.position.set(1, 0, 1) //点光源位置
    point2.position.set(0, 1, 2) //点光源位置

    engine.mScene.add(ambient)
    engine.mScene.add(point2)
    engine.mScene.add(point)
    engine.mScene.add(mesh)

    let grid = new GridHelper(50, 50, 0xffffff, 0xcccccc)
    grid.material.transparent = true
    grid.material.opacity = 0.25
    engine.mScene.add(grid)

    if (engine.mCamera.position.equals(new Vector3(0, 0, 0))) {
        engine.mCamera.position.set(10, 30, 20) //设置相机位置   
    }
    engine.mCamera.lookAt(engine.mScene.position)

    const getStandardVector = (event, domElement) => {
        let x = ((event.clientX - domElement.getBoundingClientRect().left) / domElement.offsetWidth) * 2 - 1   // 设备横坐标
        let y = -((event.clientY - domElement.getBoundingClientRect().top) / domElement.offsetHeight) * 2 + 1
        return new Vector3(x, y, 1)
    }

    const getWorldVector = (vector3, camera) => {
        return vector3.unproject(camera)
    }

    const checkIsIgnored = (item, list) => {
        for (const c of list) {
            if (item instanceof c) return true
        }
        return false
    }

    const drawRay = (scene, start, direction) => {

        let rayCaster = new Raycaster(start, direction);
        let intersects = rayCaster.intersectObjects(scene.children, false);

        if (intersects.length > 0) {
            for (const item of intersects) {
                if (checkIsIgnored(item.object, raycasterIgnore)) continue
                else console.log(item)
                break
            }
        }
    }

    const initRay = (event) => {
        let standardVector = getStandardVector(event, engine.mRenderer.domElement)
        let worldVector = getWorldVector(standardVector, engine.mCamera)
        let ray = worldVector.sub(engine.mCamera.position).normalize()


        drawRay(engine.mScene, engine.mCamera.position, ray)
    }

    engine.mRenderer.domElement.addEventListener('click', initRay)

    renderTo = engine.renderTo

    return { renderTo }
})()

export { renderTo }
